package com.canopys.study.open.test.netty.dubbo.provider;

import com.canopys.study.open.test.netty.dubbo.model.ClassInfo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.reflections.Reflections;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @Author: Canopys
 * @Descrption:
 * @Date: Created in 22:40 2020/1/14
 * @Modified By:
 */
public class InvokeHander extends ChannelInboundHandlerAdapter {

    private String getImplClassName(ClassInfo classInfo) throws Exception {
        String interfacePath = "com.canopys.study.open.test.netty.dubbo.api";
        Class superClz = Class.forName(classInfo.getClassName());
        Reflections reflections = new Reflections(interfacePath);
        Set<Class> implClassSet = reflections.getSubTypesOf(superClz);
        if (CollectionUtils.isEmpty(implClassSet)) {
            System.out.println("未找到实现类");
            return null;
        } else if (implClassSet.size() > 1) {
            System.out.println("找到多个，未明确指定哪一个");
            return null;
        } else {
            Class[] classes = implClassSet.toArray(new Class[0]);
            return classes[0].getName();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //super.channelRead(ctx, msg);

        ClassInfo classInfo = (ClassInfo) msg;
        Object clz = Class.forName(getImplClassName(classInfo)).newInstance();
        Method method = clz.getClass().getMethod(classInfo.getMethodName(), classInfo.getTypes());
        Object result = method.invoke(clz, classInfo.getObjects());
        ctx.writeAndFlush(result);

    }
}
